// License Notification
//======================================================
// Copyright (c) 2010 Channel Intelligence Inc.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// ======================================================




using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using CIP4.Common;
using CIP4.Item;

namespace CIP4.Browser
{
    public partial class ChooseTypeForm : Form
    {
        readonly LoggerDelegate Logger;

        readonly Assembly Ass;

        public Type SelectedType
        {
            get
            {
                return (Type)TypesListBox.SelectedItem; 
            }
        }

        public ChooseTypeForm(Assembly ass, LoggerDelegate logger)
        {
            InitializeComponent();
            MessageLabel.Text += Path.GetFileName(ass.Location);
            Ass = ass;
            Logger = logger;
            LoadTypes();
        }

        private void LoadTypes()
        {
            TypesListBox.Items.Clear();
            try
            {
                foreach (Type t in Ass.GetTypes())
                    if (!t.IsNested && !t.IsGenericType && t.IsPublic)
                    {
                        ConstructorInfo cons = t.GetConstructor(new Type[] { });
                        if (CIP4ItemsOnlyCheckBox.Checked)
                            if (CIP4ItemAttribute.GetAttribute(t) == null)
                                continue;
                        if (cons != null)
                            TypesListBox.Items.Add(t);
                    }
            }
            catch (ReflectionTypeLoadException ex)
            {
                string text = string.Empty;
                foreach (Exception exn in ex.LoaderExceptions)
                    text += text.Seperator(", " + Environment.NewLine) + exn.Message;
                Logger(MajorEnum.Error, MinorEnum.Generic, "Error loading assembly {0}; {1}", new object[] { Ass.Location, text });
            }
        }

        private void TypesListBox_DoubleClick(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Hide();
        }

        private void CIP4ItemsOnlyCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            LoadTypes();
        }
    }
}
